
/**
* Manage and show a popup-menu.
* Entry point: $(this).popupMenu( menu ) adds a popup menu (menu) to this node (any node).
* When a menu entry is selected, the "menu_select" event of the menu is fired with two extra params:
* - the clicked item
* - the menu
*@todo Fully implement the "disabled" for menu items
*@todo support mouseover and/or right mouse click
*@todo support submenus
*
*A menu is a ul/li list.
*/
(function($){

var
	// Hiding all menus. Used on body click and on menu show.
	hideAll = function(){
		$("ul.menu").fadeOut("fast");
	},
	// Show the menu, or hide it if already shown (maybe redoundant?)
	showMenu = function(e){
		var m=$(e.data);
		if ( m.css("display") == "none" ){
			m.css("left",e.pageX ).css("top",e.pageY ).fadeIn("fast");
		}
		else{
			m.fadeOut("fast");
		}
		return false;
	},
	// on mouse down, prepare for showing on mouseup
	mouseDown = function(e){
		hideAll();
		if ( !$(this).hasClass("disabled") ){
			$(this).one("mouseup",e.data,showMenu);
		}
		return false;
	};

// Bind menu to hook node
$.fn.popupMenu = function(menu){
	return $(this).each( function() {
		$(this).bind("mousedown",menu, mouseDown);
	});
};

// Add the menu_select event to all the menu items
Core.ObjectTypes["ul.menu"] = function(){
	$(this).find(">li:not(.disabled)").bind("click", this,
		function(e){
			$(e.data).fadeOut("fast").trigger("menu_select", this, e.data);
			return false;
		});
};

// Add the bind to the body to hide all menus when clicked generally
$("document").ready(	function(){
							$("body").bind('mousedown', hideAll );
						});

})(jQuery);